package com.qujia.common.core.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qujia.common.constant.HttpStatus;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.page.PageDomain;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.page.TableSupport;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.sql.SqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * web层通用数据处理
 *
 * @author qujia
 */
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage(PageDomain pageDomain) {
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    protected TableDataInfo failDataTable(){
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.ERROR);
        rspData.setMsg("请求参数异常");
        rspData.setRows(null);
        rspData.setTotal(0);
        return rspData;
    }

    protected TableDataInfo noEnterpriseDataTable(){
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.ERROR);
        rspData.setMsg("未创建油企");
        rspData.setRows(null);
        rspData.setTotal(0);
        return rspData;
    }

    protected TableDataInfo failUserTable(){
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.ERROR);
        rspData.setMsg("用户不存在，请重新登录");
        rspData.setRows(null);
        rspData.setTotal(0);
        return rspData;
    }

    protected TableDataInfo getNullDataTable(List<?> list) {
        TableDataInfo tableDataInfo = getDataTable(list);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        BigDecimal pageNum = new BigDecimal(pageDomain.getPageNum());
        BigDecimal pageSize = new BigDecimal(pageDomain.getPageSize());
        BigDecimal total = new BigDecimal(tableDataInfo.getTotal());
        BigDecimal totalNum = total.divide(pageSize).setScale(0, BigDecimal.ROUND_UP);
        if (pageNum.compareTo(totalNum) > 0) {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(null);
            rspData.setTotal(total.intValue());
            return rspData;
        }

        return tableDataInfo;
    }

    /***
     * 响应请求不分页
     * @param list
     * @return
     */
    protected TableDataInfo getTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }


    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjaxee(int rows) {
        AjaxResult result = new AjaxResult();
        if (rows == 1) {
            result = AjaxResult.success();
        } else if (rows == 0) {
            result = AjaxResult.error();
        } else if (rows == 2) {
            result = AjaxResult.success("小票打印机配置不正确，不能打印小票");
        }
        return result;
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }
}
